package me.zhengjie.modules.quartz.task;

import com.qiaofang.applet.common.util.RedisKeyUtil;
import com.qiaofang.applet.service.member.domain.EmployeeReport;
import com.qiaofang.applet.service.member.service.EmployeeReportService;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.MemberFocusService;
import com.qiaofang.applet.service.member.service.MemberOperateService;
import com.qiaofang.applet.service.member.service.dto.MemberFocusSimpleDto;
import com.qiaofang.applet.service.member.service.dto.MemberOperateSimpleDto;
import com.qiaofang.applet.service.member.service.dto.ReportBaseDto;
import com.qiaofang.applet.service.other.domain.CityCompany;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.service.CorporationService;
import com.qiaofang.applet.service.other.util.DateTypeUtil;
import com.qiaofang.common.util.DateUtil;
import com.qiaofang.common.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class EmployeeReportCreateTask {

    @Autowired
    private CorporationService corporationService;

    @Autowired
    private MemberOperateService memberOperateService;

    @Autowired
    private MemberFocusService memberFocusService;

    @Autowired
    private EmployeeReportService employeeReportService;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RedisUtils redisUtils;

    public void run() {
        String taskKey = RedisKeyUtil.getTaskKey(this.getClass().getSimpleName());
        if (redisUtils.hasKey(taskKey)) {
            return;
        }
        redisUtils.set(taskKey, "", 1, TimeUnit.HOURS);
        log.info("EmployeeReportCreateTask run start");
        reportProcess(null);
        log.info("EmployeeReportCreateTask run end");
        redisUtils.del(taskKey);
    }

    public void reportProcess(String dateStr) {
        Date date = null;
        if (StringUtil.isNotEmpty(dateStr)) {
            try {
                date = DateUtil.convertStringToDate(DateUtil.YYYY_MM_DD, dateStr);
            } catch (ParseException e) {
            }
        }
        Corporation corporation = new Corporation();
        corporation.setDeleted(Boolean.FALSE);
        Iterable<Corporation> list = corporationService.findAll(Example.of(corporation));
        Date finalDate = date == null ? DateTypeUtil.getYesterDay(new Date()) : date;
        list.forEach(item -> {
            String corporationCode = item.getCorporationCode();
            Map<String, List<MemberOperateSimpleDto>> operateReportData = memberOperateService.getOperateReportData(finalDate, corporationCode);
            Map<String, MemberFocusSimpleDto> focusReportData = memberFocusService.getFocusReportData(finalDate, corporationCode);
            Criteria criteria = Criteria.where("corporationCode").is(corporationCode).and("status").is(1);
            List<CityCompany> companies = mongoTemplate.find(new Query(criteria), CityCompany.class);
            companies.forEach(company -> {
                log.info("开始生成公司:{}的报表数据，开始时间:{}", company.getCompanyUuid(), new Date());
                String companyUuid = company.getCompanyUuid();
                List<ReportBaseDto> baseList = employeeService.getEmpBaseInfo(corporationCode, companyUuid);
                List<EmployeeReport> reportList = new ArrayList<>(baseList.size());
                for (ReportBaseDto reportBaseDto : baseList) {
                    EmployeeReport employeeReport = new EmployeeReport();
                    BeanUtils.copyProperties(reportBaseDto, employeeReport);
                    employeeReport.setCorporationCode(corporationCode);
                    employeeReport.setCompanyUuid(companyUuid);
                    employeeReport.setReportDate(DateTypeUtil.getDay8am(finalDate));
                    String employeeUniqueUuid = employeeReport.getEmployeeUniqueUuid();

                    MemberFocusSimpleDto focusSimpleDto = focusReportData.get(employeeUniqueUuid);
                    if (focusSimpleDto != null) {
                        employeeReport.setFocusNum(focusSimpleDto.getFocusNum());
                        employeeReport.setFansNum(focusSimpleDto.getFansNum());
                    }
                    List<MemberOperateSimpleDto> operateSimpleDtoList = operateReportData.get(employeeUniqueUuid);
                    if (!CollectionUtils.isEmpty(operateSimpleDtoList)) {
                        Set<String> exploreSet = new HashSet<>();
                        for (MemberOperateSimpleDto simpleDto : operateSimpleDtoList) {
                            Integer operateType = simpleDto.getOperateType();
                            long count = simpleDto.getCount();
                            if (operateType == 3) {
                                employeeReport.setChatNum(employeeReport.getChatNum() + count);
                            } else if (operateType == 4) {
                                employeeReport.setCallNum(employeeReport.getCallNum() + count);
                            } else if (operateType == 1) {
                                exploreSet.add(simpleDto.getMemberId());
                            } else {
                                Integer businessType = simpleDto.getBusinessType();
                                Integer shareTo = simpleDto.getShareTo();
                                switch (businessType) {
                                    case 1:
                                        if (shareTo == null || shareTo == 1) {
                                            employeeReport.setShareFirsthandWx(employeeReport.getShareFirsthandWx() + count);
                                        } else {
                                            employeeReport.setShareFirsthandPic(employeeReport.getShareFirsthandPic() + count);
                                        }
                                        break;
                                    case 2:
                                        if (shareTo == null || shareTo == 1) {
                                            employeeReport.setShareSaleWx(employeeReport.getShareSaleWx() + count);
                                        } else {
                                            employeeReport.setShareSalePic(employeeReport.getShareSalePic() + count);
                                        }
                                        break;
                                    case 3:
                                        if (shareTo == null || shareTo == 1) {
                                            employeeReport.setShareRentWx(employeeReport.getShareRentWx() + count);
                                        } else {
                                            employeeReport.setShareRentPic(employeeReport.getShareRentPic() + count);
                                        }
                                        break;
                                    case 4:
                                        if (shareTo == null || shareTo == 1) {
                                            employeeReport.setShareEmpWx(employeeReport.getShareEmpWx() + count);
                                        } else {
                                            employeeReport.setShareEmpPic(employeeReport.getShareEmpPic() + count);
                                        }
                                        break;
                                }
                            }
                        }
                        employeeReport.setVisitNum(exploreSet.size());
                    }
                    employeeReport.setAll();
                    reportList.add(employeeReport);
                }
                employeeReportService.saveAll(reportList);
                log.info("公司:{}的报表数据保存成功，结束时间:{}", company.getCompanyUuid(), new Date());
            });
        });
    }
}
